<script>
export default {
    methods:{
        
        // 添加水印2
        async imgToCanvas(url) {
            // 创建img元素
            const img = document.createElement("img");
            img.src = url;
            img.setAttribute("crossOrigin", "anonymous"); // 防止跨域引起的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
            await new Promise((resolve) => (img.onload = resolve));
            // 创建canvas DOM元素，并设置其宽高和图片一样
            const canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            // 坐标(0,0) 表示从此处开始绘制，相当于偏移。
            canvas.getContext("2d").drawImage(img, 0, 0);
            return canvas;
        },
        /**
            * canvas添加水印3
            * @param {canvas对象} canvas
            * @param {水印文字} text
            */
        addWatermark(canvas, text) {
            const ctx = canvas.getContext("2d");
            ctx.rotate(-30 * Math.PI / 180) // 水印旋转角度
            ctx.font = '40px Vedana'
            ctx.fillStyle = 'rgb(0,0,0,.1)'
            ctx.textAlign = 'center'
            ctx.textBaseline = 'Middle'
            let zby = canvas.height / 4
            for(let j = 1; j < 4; j++) {
                ctx.fillText(text, 150, zby * j)
            }
            /* let forIndex = canvas.width / 200 | 0
            for(let i = -10; i < 10; i++) {
                for(let j = -10; j < forIndex; j++) {
                    ctx.fillText(text, 600 * j, 300 * i + 150)
                }
            } */
            return canvas;
        },

        /**
        * canvas转成img
        * @param {canvas对象} canvas
        */
        convasToImg(canvas) {
            // 新建Image对象，可以理解为DOM
            var image = new Image();
            // canvas.toDataURL 返回的是一串Base64编码的URL
            // 指定格式 PNG
            image.src = canvas.toDataURL("image/jpeg");
            return image;
        },
    }
}
</script>
